<template>
  <el-dialog v-model="dialogFormVisible" title="单车结算" width="500px" destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="160px">
      <el-form-item label="Call车尾款 :" prop="payMoney">
        <el-input v-model="form.payMoney" autocomplete="off" placeholder="请输入Call车尾款" />
      </el-form-item>
      <el-form-item label="尾款结算日期 :" prop="payMoneyTime">
        <el-date-picker
          v-model="form.payMoneyTime"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="请选择尾款结算日期"
        />
      </el-form-item>
      <el-form-item label="支付利息 :" prop="payInterest">
        <el-input v-model="form.payInterest" autocomplete="off" placeholder="请输入支付利息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, defineExpose, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import useDialogForm from '@/hooks/useDialogForm';
import { validateMoney } from '@/utils/validate';
import { createSettleRecordApi } from '@/api/account_manage';

const { formRef, dialogFormVisible, validateForm } = useDialogForm();

const handleOpen = (row: any) => {
  const { callPrice } = row;
  const { bond } = row;
  form.payMoney = (callPrice * 100 - bond * 100) / 100;
  form.carId = row.id;
  form.callId = row.callId;
  dialogFormVisible.value = true;
};
type Form = {
  callId: string | number;
  carId: string | number;
  payMoney: string | number | any;
  payMoneyTime: string | number | any;
  payInterest: string | number | any;
};
const form = reactive<Form>({
  callId: '',
  carId: '',
  payMoney: '0.00',
  payMoneyTime: '',
  payInterest: '0.00',
});
const handleSubmit = async () => {
  try {
    await validateForm();
    const res = await createSettleRecordApi(form);
    const { code, msg } = res;
    if (code === 10000) {
      ElMessage.success(msg);
      emit('handleRefresh');
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(msg);
    }
  } catch (e) {
    console.error(e);
  }
};

const rules = reactive<any>({
  payMoney: [
    { required: true, message: '请输入Call车尾款', trigger: 'change' },
    { validator: validateMoney, trigger: 'change' },
  ],
  payMoneyTime: [{ required: true, message: '请选择尾款结算日期', trigger: 'change' }],
  payInterest: [
    { required: true, message: '请输入支付利息', trigger: 'change' },
    { validator: validateMoney, trigger: 'change' },
  ],
});

const emit = defineEmits(['handleRefresh']);
defineExpose({ handleOpen });
</script>

<style scoped></style>
